<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, string $role)
    {
        $user = Auth::user();

        // 检查用户是否登录
        if (!$user) {
            return response()->json([
                'success' => false,
                'code' => 401,
                'message' => '用户未登录',
                'timestamp' => now()->toISOString(),
            ], 401);
        }

        // 检查用户状态
        if ($user->status !== 'active') {
            return response()->json([
                'success' => false,
                'code' => 403,
                'message' => '用户账户已被禁用',
                'timestamp' => now()->toISOString(),
            ], 403);
        }

        // 检查用户角色
        if (!$user->hasRole($role)) {
            return response()->json([
                'success' => false,
                'code' => 403,
                'message' => '角色权限不足',
                'timestamp' => now()->toISOString(),
            ], 403);
        }

        return $next($request);
    }
}